package com.stockz.core.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.stockz.core.dao.ScripDao;
import com.stockz.core.model.Scrip;

@Service
@Transactional
public class ScripManager {
	
	@Autowired
	private ScripDao scripDao;
	private final List<Scrip> allScripList = new ArrayList<Scrip>();
	private final Map<Date,List<Scrip>> dateScripMap = new HashMap<Date,List<Scrip>>();
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void updateScripForDate(Scrip scrip, Date date){
		if(!allScripList.contains(scrip)){
			persist(scrip);
		}
		List<Scrip> scripList = dateScripMap.get(date);
		if(scripList != null && !scripList.contains(scrip)){
			scripList.add(scrip);
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
	public Scrip getScrip(String code){
		return scripDao.getScrip(code);
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void persist(Scrip scrip) {
		if(!allScripList.contains(scrip)){
			scripDao.persist(scrip);
			allScripList.add(scrip);
		}
	}

	private static boolean allScripFetched = false;
	@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
	public List<Scrip> getAllScrip() {
		if(!allScripFetched){
			allScripList.addAll(scripDao.getAllScrip());
			allScripFetched = true;
		}
		return allScripList;
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
	public List<Scrip> getAllScrip(Date date){
		List<Scrip> scripList = dateScripMap.get(date);
		if(scripList == null || scripList.isEmpty()){
			scripList = scripDao.getAllScrip(date);
			dateScripMap.put(date, scripList);
			return scripList;
		}
		return scripList;
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
	public List<Scrip> getAllScrip(String type){
		return scripDao.getAllScrip(type);
	}
	
}
